﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RenderEngineInterfaces;
using System.ComponentModel.Composition;
using System.IO;
using System.Threading.Tasks;
using DeepZoomPivotConstructor.VisualLib;
using System.Drawing;
using System.Drawing.Imaging;
using DeepZoomPivotConstructor.ErrorAndLoggingInterfaces;

namespace SimpleFileRendering
{
    /// <summary>
    /// Convert a GIF image into a PNG image so that it can be correctly
    /// rendered by the DZ software.
    /// </summary>
    [Export(typeof(IRenderItem))]
    [RenderInfo(typeof(FileInfo))]
    public class GIFFileRender : IRenderItem
    {
        /// <summary>
        /// The local render engine - so we can render the resulting png
        /// </summary>
        [Import]
        private IRenderEngine RenderEngine { get; set; }

        /// <summary>
        /// If we should be using a different temp directory than the one that is there by default... :-)
        /// </summary>
#pragma warning disable 0649
        [Import("RenderingTempDir", AllowDefault = true)]
        private DirectoryInfo RenderingTempDir;
#pragma warning restore 0649

        /// <summary>
        /// Error logger to get the message out if we have a failure here!
        /// </summary>
#pragma warning disable 0649
        [Import(AllowDefault = true)]
        private IErrorLogger MyLogger;
#pragma warning restore 0649

        /// <summary>
        /// Do the conversion
        /// </summary>
        /// <param name="what"></param>
        /// <returns></returns>
        public Task<Visual> Render(object what)
        {
            return Task<Visual>.Factory.StartNew(() => RunRender(what as FileInfo));
        }

        /// <summary>
        /// Does the actual work of turning a gif into a png
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <returns></returns>
        private Visual RunRender(FileInfo fileInfo)
        {
            ///
            /// Get a temp file to write to!
            /// 

            string filedir;
            if (RenderingTempDir != null)
            {
                filedir = RenderingTempDir.FullName;
            }
            else
            {
                filedir = Path.GetTempPath();
            }
            FileInfo tempFile = new FileInfo(filedir + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".png");

            ///
            /// Do the conversion now!
            /// 

            try
            {
                using (var imgStream = tempFile.Create())
                {
                    Image.FromFile(fileInfo.FullName).Save(imgStream, ImageFormat.Png);
                    imgStream.Close();
                }
            }
            catch (Exception e)
            {
                if (MyLogger != null)
                {
                    MyLogger.LogMessage("GIFFileRender", "Corrupt GIF file, error when opening it! Ignored!", e);
                }
                return null;
            }

            ///
            /// Ok! We have it. Now get the real deal back!
            /// 

            return RenderEngine.Render(tempFile);
        }

        /// <summary>
        /// Check to see if we can actually do the work (is this a gif file?).
        /// </summary>
        /// <param name="what"></param>
        /// <returns></returns>
        public RenderPluginPriority RenderPriority(object what)
        {
            FileInfo f = what as FileInfo;
            if (!f.Exists)
            {
                return RenderPluginPriority.RPPCantDoIt;
            }

            string ext = f.Extension.ToLower();
            if (ext == ".gif")
            {
                return RenderPluginPriority.RPPGeneric;
            }

            return RenderPluginPriority.RPPCantDoIt;
        }
    }
}
